using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Text.RegularExpressions;

public partial class Pages_Admin_AddAccount : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    protected void clearAll()
    {
        txtUserName.Text = "";
        txtPassword.Text = "";
        txtFullName.Text = "";
        txtAddress.Text = "";
        txtPhoneNumber.Text = "";
        txtEmail.Text = "";
        ddlRole.SelectedIndex = 0;
        ddlBranch.SelectedIndex = 0;
    }

    /// <summary>
    /// Save input data in database
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";
        txtUserName.Text = txtUserName.Text.ToLower();
        if (Page.IsValid)
        {
            try
            {
                int result;
                result = DALAccount.InsertAccount(txtUserName.Text, txtPassword.Text, txtFullName.Text, txtAddress.Text, txtEmail.Text, txtPhoneNumber.Text, ddlRole.SelectedValue, ddlBranch.SelectedValue);
                if (result > 0) //Success
                {
                    clearAll();
                    lblMessage.Text = "New account was added successfully";
                }
                else
                {
                    lblMessage.Text = "Error adding new account";
                }
            }
            catch 
            {
                lblMessage.Text = "Error adding new account";
            }
        }
    }

    /// <summary>
    /// This webmethod checks whether a username is available or not
    /// </summary>
    /// <param name="id">id</param>
    /// <returns>true if the parameter is an available username, false otherwise</returns>
    [WebMethod]
    public static int IsAvailableUserName(string userName)
    {
        
        userName = userName.ToLower();
        Regex userNamePattern = new Regex(@"^[\d\w]{6,12}$");
        if (!userNamePattern.IsMatch(userName))
            return -1;
        Account account = DALAccount.GetOneAccount(userName);
        if (account == null || account.UserName == "")
            return 1;
        else
            return 0;
    }
}
